package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.TBackRole;
import model.VBackAdminUser;
import model.VBackRoleSystemModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import annotation.Log;
import persistent.factory.DAOFactory;
import util.office.WriteExcel;
import util.toolkit.Constant;
import util.toolkit.Expression;
import util.toolkit.ResponseJSON;

/**
 * 网站后台系统管理
 * 
 * @author djf
 * @since 2018/11/21
 */

@Controller
@RequestMapping(value = "/sysbackmanage")
public class SysBackManagementController {

	/**
	 * 添加一个后台管理角色控制类
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 添加一个后台管理角色控制类
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "添加一个后台管理角色", operationClassPath = "controller.SysBackManagementController.addBackRole(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "系统管理/角色管理")
	@RequestMapping(value = "/addbackrole")
	public String addBackRole(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TBackRole backrole = new TBackRole();

		try {
			String rolename = req.getParameter("rolename");
			String roledescr = req.getParameter("roledescr");

			if (rolename != null && !rolename.equals("") && roledescr != null && !roledescr.equals("")) {
				backrole.setName(rolename);
				backrole.setDescription(roledescr);
				backrole.setDeepth(1);
				backrole.setParentid(0);
				boolean row = DAOFactory.getBackRoleDAO().addBackRole(backrole);
				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "角色信息添加成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "角色信息添加失败！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "角色信息添加失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "角色信息添加失败！");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}

	/**
	 * 修改一条管理员角色信息
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 修改一条管理员角色信息
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "修改一个后台管理角色", operationClassPath = "controller.SysBackManagementController.updateBackRole(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "系统管理/角色管理")
	@RequestMapping(value = "/updatebackrole")
	public String updateBackRole(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TBackRole backrole = new TBackRole();

		try {
			String roleid = req.getParameter("roleid");
			String rolename = req.getParameter("rolename");
			String roledescr = req.getParameter("roledescr");

			if (roleid != null && !roleid.equals("") && rolename != null && !rolename.equals("") && roledescr != null
					&& !roledescr.equals("")) {
				backrole = DAOFactory.getBackRoleDAO().getTBackRole(Integer.parseInt(roleid));
				backrole.setName(rolename);
				backrole.setDescription(roledescr);

				boolean row = DAOFactory.getBackRoleDAO().updateRole(backrole);
				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "角色信息修改成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "角色信息修改失败！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "角色信息修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "角色信息修改失败！");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 将一个后台管理员角色启用或禁用
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 将一个后台管理员角色启用或禁用
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "启用或禁用后台管理角色", operationClassPath = "controller.SysBackManagementController.enableBackRole(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "系统管理/角色管理")
	@RequestMapping(value = "/enablebackrole")
	public String enableBackRole(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TBackRole backrole = new TBackRole();

		try {
			String roleid = req.getParameter("roleid");
			String rolestatus = req.getParameter("rolestatus");

			if (roleid != null && !roleid.equals("") && rolestatus != null && !rolestatus.equals("")) {
				backrole = DAOFactory.getBackRoleDAO().getTBackRole(Integer.parseInt(roleid));
				backrole.setStatus(rolestatus);

				boolean row = DAOFactory.getBackRoleDAO().updateRole(backrole);
				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "角色信息修改成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "角色信息修改失败！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "角色信息修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "角色信息修改失败！");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 得到后台管理的全部角色（不带分页），加载角色下拉框
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 得到后台管理的全部角色（不带分页），加载角色下拉框
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询后台管理角色", operationClassPath = "controller.SysBackManagementController.getAllBackRoleList(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "系统管理/角色管理")
	@RequestMapping(value = "/getallbackrolelist")
	public String getAllBackRoleList(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();

		try {
			exp.andEqu("parentid", 0, Integer.class);
			exp.andEqu("deepth", 1, Integer.class);
			String strwhere = exp.toString();
			List<TBackRole> list = DAOFactory.getBackRoleDAO().getBackRoleList(strwhere);
			if (list != null && list.size() > 0) {
				result.put("code", 0);
				result.put("msg", "角色信息加载成功");
				result.put("count", list.size());
				JSONArray jsonArray = JSONArray.fromObject(list);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "角色信息加载失败");
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 2);
			result.put("msg", "角色信息加载失败");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 得到后台管理的全部角色(不要分页)
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 得到后台管理的全部角色(不要分页)
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询后台管理角色", operationClassPath = "controller.SysBackManagementController.getBackRoleList(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "系统管理/角色管理")
	@RequestMapping(value = "/getbackrolelist")
	public String getBackRoleList(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();

		try {

			exp.andEqu("parentid", 0, Integer.class);
			exp.andEqu("deepth", 1, Integer.class);
			String strwhere = exp.toString();
			List<TBackRole> list = DAOFactory.getBackRoleDAO().getBackRoleList(strwhere);
			if (list != null && list.size() > 0 && list.size() > 0) {
				result.put("code", 0);
				result.put("msg", "角色信息查询成功");
				result.put("count", list.size());
				JSONArray jsonArray = JSONArray.fromObject(list);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果");
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 1);
			result.put("msg", "查询失败");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 根据角色得到角色权限列表
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 根据角色得到角色权限列表
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "根据角色查询角色权限", operationClassPath = "controller.SysBackManagementController.getBackRoleModelByRole(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "系统管理/权限管理")
	@RequestMapping(value = "/getbackrolemodelbyrole")
	public String getBackRoleModelByRole(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();

		try {
			String roleid = req.getParameter("roleid");

			if (roleid != null && !roleid.equals("")) {
				exp.andEqu("roleid", Integer.parseInt(roleid), Integer.class);
				exp.andEqu("menuDeepth", 0, Integer.class);

				String strwhere = exp.toString();
				List<VBackRoleSystemModel> list = DAOFactory.getBackRoleDAO().getBackRoleSystemModel(strwhere);

				if (list != null && list.size() > 0) {
					result.put("code", 0);
					result.put("msg", "角色权限查询成功");
					result.put("count", list.size());
					JSONArray jsonArray = JSONArray.fromObject(list);
					result.element("data", jsonArray);
				} else {
					result.put("code", 1);
					result.put("msg", "无查询结果");
				}
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果");
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 2);
			result.put("msg", "角色权限查询失败");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}

	/**
	 * 取消授权处理类
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 取消授权处理类
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "取消一个角色的菜单权限", operationClassPath = "controller.SysBackManagementController.disEnablePower(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "系统管理/权限管理")
	@RequestMapping(value = "/rolemanagementdisenablepower")
	public String disEnablePower(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();

		try {
			String powerid = req.getParameter("powerid"); // 角色id

			if (powerid != null && !powerid.equals("")) {
				boolean row = DAOFactory.getBackRoleDAO().disEnable(Integer.parseInt(powerid));

				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "取消授权成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "取消授权失败，请重试！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "取消授权失败，请重试！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "取消授权失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}

	/**
	 * 授权处理类
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 授权处理类
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "给一个角色添加菜单权限", operationClassPath = "controller.SysBackManagementController.enablePower(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "系统管理/权限管理")
	@RequestMapping(value = "/rolemanagementenablepower")
	public String enablePower(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();

		try {
			String powerid = req.getParameter("powerid");// 角色id

			if (powerid != null && !powerid.equals("")) {

				boolean row = DAOFactory.getBackRoleDAO().enable(Integer.parseInt(powerid));

				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "授权成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "授权失败，请重试！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "授权失败，请重试！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "授权失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}

	/**
	 * 根据角色获得菜单列表
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 根据角色获得菜单列表
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "根据角色查询菜单", operationClassPath = "controller.SysBackManagementController.getBackMenuByRole(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "系统管理/权限管理")
	@RequestMapping(value = "/getbackmenulbyrole")
	public String getBackMenuByRole(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();
		HttpSession session = req.getSession();

		try {
			VBackAdminUser backuser = (VBackAdminUser) session.getAttribute("backUser");
			Integer roleid = backuser.getRoleId();
			if (roleid != null && !roleid.equals("")) {
				exp.andEqu("roleid", roleid, Integer.class);
				exp.andEqu("isedit", true, Boolean.class);
				exp.orderByAsc("displayorder");
				String strwhere = exp.toString();
				List<VBackRoleSystemModel> list = DAOFactory.getBackRoleDAO().getBackRoleSystemModelMenu(strwhere);

				if (list != null && list.size() > 0) {
					result.put("code", 0);
					result.put("msg", "菜单查询成功");
					result.put("count", list.size());
					JSONArray jsonArray = JSONArray.fromObject(list);
					JSONArray jsonArray2 = JSONArray.fromObject(backuser);
					result.element("data", jsonArray);
					result.element("loginuser", jsonArray2);
				} else {
					result.put("code", 1);
					result.put("msg", "无查询结果");
				}
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果");
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 2);
			result.put("msg", "菜单查询失败");
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}

	/**
	 * 删除导出的Excel的文件控制类（下载完成后调用）(2018-12-12 徐震霖)
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 删除导出的Excel的文件控制类（下载完成后调用）
	@RequestMapping(value = "/deleteparstutable")
	public String deleteParStuTable(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		HttpSession session = req.getSession();

		try {

			// 后期从session里获取用户信息
			VBackAdminUser user = (VBackAdminUser) session.getAttribute("backUser");

			// TODO 2018-2-14修改
			// 删除的文件路径
			// Linux系统下的删除路径
			// String path = "后台管理员下载/" + user.getUserid().trim();
			// Windows系统下的删除路径
			String path = "后台管理员下载\\" + user.getUserid().trim();

			if (WriteExcel.delAllFile(path)) {
				result.put("code", ResponseJSON.FLAG_SUCC);
				result.put("msg", "删除成功！");
			} else {
				result.put("code", ResponseJSON.FLAG_SUCC);
				result.put("msg", "暂无文件或删除失败！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_SUCC);
			result.put("msg", "暂无文件或删除失败！");
			e.printStackTrace();
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}

}
